package com.ksd.web.controller.system;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ksd.common.annotation.Log;
import com.ksd.common.config.PlayControlConfig;
import com.ksd.common.core.controller.BaseController;
import com.ksd.common.core.domain.AjaxResult;
import com.ksd.common.enums.BusinessType;
import com.ksd.common.utils.StringUtils;
import com.ksd.quartz.http.DRMHttpClient;
import com.ksd.quartz.util.TaskConstans;
import com.ksd.system.domain.SysBoard;
import com.ksd.system.domain.SysChannel;
import com.ksd.system.domain.SysChannelTemplate;
import com.ksd.system.service.ISysBoardService;
import com.ksd.system.service.ISysChannelService;
import com.ksd.system.service.ISysChannelTemplateService;
import com.ksd.system.service.ISysOperLogService;
import com.ksd.web.controller.m3beans.*;
import com.ksd.web.controller.process.ProcessVO;
import com.ksd.web.controller.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 频道搜索Controller
 * 
 * @author y.wu
 * @date 2025-01-08
 */
@RestController
@RequestMapping("/system/channelSearchOneRestart")
public class SysChannelSearchOneRestartController extends BaseController
{

    public final Logger logger = LoggerFactory.getLogger(SysChannelSearchOneRestartController.class);

    @Autowired
    private SendChannelService sendChannelService;

    @Autowired
    private ISysBoardService sysBoardService;
    @Autowired
    private ISysOperLogService sysOperLogService;

    @Autowired
    private ISysChannelTemplateService sysChannelTemplateService;
    @Autowired
    private SearchChannelService searchChannelService;
    @Autowired
    private OutputChannelService outputChannelService;
    @Autowired
    private ISysChannelService sysChannelService;

    @PostMapping("/clearAgainScanById")
    public AjaxResult clearAgainScanById(@RequestBody SysBoard sysBoardTemp){
        logger.info("开始进行一键配置频道功能:"+sysBoardTemp.getId());
        Boolean clearChannleFlag = false;
        SysBoard sysBoard = sysBoardService.selectSysBoardById(sysBoardTemp.getId());
        logger.info("开始进行清除操作:"+sysBoard.getUrl()+"========="+sysBoard.getId());
        int resetResult = searchChannelService.resetProgramDbsData(sysBoard);
        logger.info("清除频道接口结果:"+resetResult);
        if (resetResult == 0) {
            logger.info("频道清除成功,开始进行循环查询");
            return success("清除直播板卡:"+sysBoard.getId()+" 频道成功,开始搜索频道");
        }else{
            logger.error("清除直播板卡:"+sysBoard.getId()+" 频道失败,请检查网络连接."+sysBoard.getUrl());
            return error();
        }
    }
    @PostMapping("/startSearchChannel")
    public AjaxResult startSearchChannel(@RequestBody SysBoard sysBoardTemp){
        logger.info("开始启动频道搜索:"+sysBoardTemp.getId());
        SysBoard sysBoard = sysBoardService.selectSysBoardById(sysBoardTemp.getId());
        StartChannelScanData startChannelScanData = new StartChannelScanData();
        startChannelScanData.setBoard(sysBoard.getId().toString());
        startChannelScanData.setPolarization(3);//左旋或右旋
        startChannelScanData.setSymbolRate(28800);
        startChannelScanData.setFrequency(12020);
        int startResult = searchChannelService.startChannelScan(sysBoard, startChannelScanData);
        logger.info("开始搜索结果:"+startResult);
        if (startResult == 0) {
            return success("搜索启动成功");
        }else{
            return error("搜索启动失败");
        }
    }
    @PostMapping("/searchChannel")
    public AjaxResult searchChannel(@RequestBody SysBoard sysBoardTemp){
        logger.info("正在进行频道搜索:"+sysBoardTemp.getId());
        SysBoard sysBoard = sysBoardService.selectSysBoardById(sysBoardTemp.getId());
        int searchResult = searchChannelService.repeatedSearchM3GetService(sysBoard);
        logger.info("板卡搜索结果:"+searchResult);
//        if (searchResult == 1) {
//            return success("直播板卡"+sysBoardTemp.getId()+" 正在进行频道搜索,请等待");
//        }else{
//            return error("直播板卡"+sysBoardTemp.getId()+" 频道搜索失败");
//        }
        return success(searchResult);//将搜索结果直接传给前端,前端根据搜索结果判断是否要持续搜索(1) (0)搜索完成 (其他-1,2搜索失败)
    }
    @PostMapping("/stopChannel")
    public AjaxResult stopChannel(@RequestBody SysBoard sysBoardTemp){
        logger.info("开始停止频道搜索:"+sysBoardTemp.getId());
        SysBoard sysBoard = sysBoardService.selectSysBoardById(sysBoardTemp.getId());
        int stopResult = searchChannelService.stopChannelScanNoGetInfo(sysBoard);
        if (stopResult == 0) {
            return success("直播板卡"+sysBoardTemp.getId()+"停止搜索节目成功");
        }else{
            return error("直播板卡"+sysBoardTemp.getId()+" 搜索节目失败");
        }
    }
    @PostMapping("/getChannelInfo")
    public AjaxResult getChannelInfo(@RequestBody SysBoard sysBoardTemp){
        logger.info("开始获取直播板卡所有待分发的平台:"+sysBoardTemp.getId());
        SysBoard sysBoard = sysBoardService.selectSysBoardById(sysBoardTemp.getId());
        AjaxResult channelListManage = sendChannelService.getChannelListManage(sysBoard.getId());
        return channelListManage;
    }

    @PostMapping("/setChannelInfoRestart")
    public AjaxResult setChannelInfoRestart(@RequestBody SysBoard sysBoardTemp){
        logger.info("开始对直播板卡分发的默认平台:"+sysBoardTemp.getId());
        SysBoard sysBoard = sysBoardService.selectSysBoardById(sysBoardTemp.getId());
        AjaxResult channelListManage = setSysChannleUpdate(sysBoard);
        return channelListManage;
    }

    public AjaxResult setSysChannleUpdate(SysBoard sysBoard) {
        logger.info("开始进行默认分发频道设置:"+sysBoard.getUrl());
        //在停止查询接口会进行频道搜索,会将所有频道重新插入数据库中,等待1秒
        //查询频道表是否有数据,如果有数据,开始进行频道默认分发处理
        List<SysChannel> sysChannels = new ArrayList<>();
        if (TaskConstans.boardValue1.equals(sysBoard.getId().toString())) {
            logger.info("直播板卡1");
            sysChannels = sysChannelService.selectSysChannelList(new SysChannel(), SysChannel.table_one);
            logger.info("个数:"+sysChannels.size());
        }else if(TaskConstans.boardValue2.equals(sysBoard.getId().toString())) {
            logger.info("直播板卡2");
            sysChannels = sysChannelService.selectSysChannelList(new SysChannel(), SysChannel.table_twice);
            logger.info("size:"+sysChannels.size());
        }
        logger.info("查询到的最新频道列表数据个数:"+sysChannels.size()+"============直播板卡id:"+sysBoard.getId());
        if (sysChannels.size() != 0) {
            logger.info("开始进行直播板卡:" + sysBoard.getId() + " 的节目分发");
            SysChannelTemplate sysChannelTemplate = new SysChannelTemplate();
            sysChannelTemplate.setPush(sysBoard.getId());
            List<SysChannelTemplate> sysChannelTemplates = sysChannelTemplateService.selectSysChannelTemplateList(sysChannelTemplate);
            logger.info("该直播板卡设置的默认配置的频道个数:" + sysChannelTemplates.size());
            //进行默认分发
            DeliveryParamObject deliveryParamObject = new DeliveryParamObject();
            deliveryParamObject.setBordId(sysBoard.getId().toString());
            Set<String> freqs = new HashSet<>();
            List<SysChannel> selectedChannels = new ArrayList<>();


            List<SaveServiceInfo> saveServiceInfoList = new ArrayList<>();
            for (SysChannelTemplate channelTemplate : sysChannelTemplates) {
                String name = channelTemplate.getName();
                SysChannel sysChannel = new SysChannel();
                if (TaskConstans.boardValue1.equals(sysBoard.getId().toString())) {
                    sysChannel = sysChannelService.selectSysChannelByName(name, SysChannel.table_one);
                } else if (TaskConstans.boardValue2.equals(sysBoard.getId().toString())) {
                    sysChannel = sysChannelService.selectSysChannelByName(name, SysChannel.table_twice);
                }
                if (sysChannel != null) {
                    selectedChannels.add(sysChannel);//默认选中的分发频道
                    logger.info("选中默认配置的频道有:" + sysChannel.getName() + "=====频道表:" + sysChannel.getId() + "==============" + sysChannel.getFreq());
                    //默认分发频道有限制,当前默认分发频道个数为不允许超过6个
                    freqs.add(sysChannel.getFreq().toString());
                }
            }

            //重新针对各个高频头选择默认分发
            List<SysChannel> selectedChannelsCountList = new ArrayList<>();
            for (String everyFreq : freqs) {
                //有2个高频头,平均每个分配2个频道
                int count = 0;
                for (SysChannel selectedChannel : selectedChannels) {
                    Long freq = selectedChannel.getFreq();
//                    if (everyFreq.equals(freq.toString()) && count < Long.valueOf(PlayControlConfig.getSelectSysChannelSingleCount())) {
                    if (everyFreq.equals(freq.toString())) {
                        selectedChannelsCountList.add(selectedChannel);
                        count ++;
                    }
                }
            }
            logger.info("设置默认分发频道个数:" + selectedChannels.size() + ",频率freqs size:" + freqs.size());
            selectedChannels = new ArrayList<>();
            for (SysChannel sysChannel : selectedChannelsCountList) {
                selectedChannels.add(sysChannel);
            }
            logger.info("重新根据当前直播板卡每次最多允许配置频道个数,设置默认分发频道个数:" + selectedChannels.size() + ",频率freqs size:" + freqs.size());
            List<DeliveryParam> deliveryParam = new ArrayList<>();
            for (String freq : freqs) {
                DeliveryParam delivery = new DeliveryParam();
                delivery.setSymbolRate(28800);
                delivery.setPolarization(3);
                delivery.setFrequency(Integer.valueOf(freq));
                deliveryParam.add(delivery);
            }
            deliveryParamObject.setDeliveryParam(deliveryParam);

            int mainFreqExResult = outputChannelService.setMainFreqEx(sysBoard, deliveryParamObject);
            logger.info("==========开始进行设置默认分发频道,setMainFreqEx接口结果:" + mainFreqExResult);
            if (mainFreqExResult == 0) {

                for (String freq : freqs) {
                    List<SaveService> serviceInfoObjectList = new ArrayList<>();
                    Long onid = 0L;
                    Long tsid = 0L;
                    Long symbolRate = 0L;
                    SaveServiceInfo saveServiceInfo = new SaveServiceInfo();
                    for (int i = 0; i < selectedChannels.size(); i++) {
                        SysChannel selectedChannel = selectedChannels.get(i);
                        Long freqResult = selectedChannel.getFreq();
                        if (freq.equals(freqResult.toString())) {
//                            logger.info("freqResult:" + freqResult);
                            logger.info("freqResult:" + freqResult+",默认选中:" + selectedChannel.getName());
                            onid = selectedChannel.getOnid();
                            tsid = selectedChannel.getTsid();
//                            logger.info(onid + "===================tsId:" + tsid);
//                                                symbolRate = selectedChannel.getSymbolRate();
                            SaveService serviceInfoObject = new SaveService();
                            serviceInfoObject.setId(Integer.valueOf(selectedChannel.getPmtpid().toString()));
                            serviceInfoObject.setName(selectedChannel.getName());
                            serviceInfoObject.setProtocol("udp");
                            serviceInfoObject.setIp(selectedChannel.getIp());
                            serviceInfoObject.setPort(Integer.valueOf(selectedChannel.getPort()));
                            serviceInfoObject.setUrl("");
                            serviceInfoObjectList.add(serviceInfoObject);
                        }
                    }
                    logger.info("saveServiceList:" + serviceInfoObjectList.size());
                    saveServiceInfo.setServiceinfo(serviceInfoObjectList);
                    saveServiceInfo.setOnid(Integer.valueOf(onid.toString()));
                    saveServiceInfo.setTsid(Integer.valueOf(tsid.toString()));
//                                        saveServiceInfo.setFrequency(Integer.valueOf(freq.toString()));
//                                        saveServiceInfo.setSymbolRate(Integer.valueOf(symbolRate.toString()));
                    saveServiceInfoList.add(saveServiceInfo);
                }
                //开始进行保存
                SaveSatelliteInfo saveSatelliteInfo = new SaveSatelliteInfo();
                saveSatelliteInfo.setBoard(sysBoard.getId().toString());
                saveSatelliteInfo.setSatellite("1");//1表示高频头1  2表示高频头2
                saveSatelliteInfo.setServiceInfo(saveServiceInfoList);
                logger.info("开始设置重新分发默认频道");
                AjaxResult ajaxResult = outputChannelService.setPrfDataSave(sysBoard, saveSatelliteInfo);
                logger.info("======保存频道结果========:" + ajaxResult.toString());
                if (ajaxResult != null && ajaxResult.isSuccess()) {
                    //开始获取最新频道
                    QueryInfo queryInfo = new QueryInfo();
                    queryInfo.setBoard(sysBoard.getId().toString());
                    int getPrfDataListResult = outputChannelService.getPrfDataList(sysBoard, queryInfo);
                    logger.info("设置默认分发频道结果:" + getPrfDataListResult);
                    if (getPrfDataListResult == 0) {
                        logger.info("===================重置分发频道成功===========================");
                        return success();
                    }else{
                        return error("保存设置直播板卡:"+sysBoard.getId()+"默认分发频道失败，请检查网络连接");
                    }
                }
                logger.info("直播板卡:" + sysBoard.getId() + " ,设置默认分发频道结束:" + sysBoard.getUrl());
                return ajaxResult;
            }
        }
        return error("设置直播板卡:"+sysBoard.getId()+"默认分发频道失败，请检查网络连接");
    }


}
